from django.contrib.messages.storage import default_storage
from django.core.cache import caches
from django.http import HttpResponse
import json
from django.utils.deprecation import MiddlewareMixin


# 用户代理中间件
class UserArgentMiddleware(MiddlewareMixin):


    def process_request(self, request):
        print("自定义中间件UserArgentMiddleware，请求")

    def process_response(self, request, response):
        print("自定义中间件UserArgentMiddleware，响应")
        return response


# 禁用ip中间件
class BanIpMiddleware(MiddlewareMixin):

    def process_request(self, request):
        print("自定义中间件BanIpMiddleware，请求")

    def process_response(self, request, response):
        # print("自定义中间件BanIpMiddleware，响应")
        # print(request.META['REMOTE_ADDR'])


        cache = caches["redis"]
        # 获取已经封禁的ip
        ips_list = json.loads(cache.get("ips")) if cache.get("ips") else []
        # 判断当前ip是否被封禁
        if request.META['REMOTE_ADDR'] in ips_list:
            return HttpResponse("小可爱你迷路了")
        else:
            # 更新被封禁的ip
            ips_list.append(f'{request.META['REMOTE_ADDR']}')
        # 将更新后的被封禁ip缓存到数据库
        ips = json.dumps(ips_list)
        cache.set("ips",ips)

        return response
